package com.example.api.controller;

import com.example.api.vo.UserApiVO;
import com.example.common.util.RequestContext;
import com.example.common.vo.ApiResponse;
import com.example.common.vo.PageResponse;
import com.example.query.UserQuery;
import com.example.service.UserService;
import com.example.web.vo.UserQueryVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户开放API控制器
 * 负责对内/外部开放系统能力，将Service层接口封装为HTTP接口形式
 * 
 * @author AI Assistant
 * @since 1.0.0
 */
@Api(tags = "用户查询API")
@Slf4j
@RestController
@RequestMapping("/api/v1/users")
public class UserApiController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 分页查询用户列表
     * 
     * @param username 用户名（模糊查询）
     * @param realName 真实姓名（模糊查询）
     * @param email 邮箱（模糊查询）
     * @param phone 手机号（模糊查询）
     * @param status 用户状态：0-禁用，1-启用
     * @param pageNum 页码，从1开始，默认1
     * @param pageSize 每页大小，默认10，最大100
     * @return 用户分页数据
     */
    @ApiOperation(value = "分页查询用户列表", notes = "支持多条件模糊查询，分页返回用户列表")
    @GetMapping
    public ApiResponse<PageResponse<UserApiVO>> queryUsers(
            @ApiParam(value = "用户名", example = "admin") @RequestParam(required = false) String username,
            @ApiParam(value = "真实姓名", example = "管理员") @RequestParam(required = false) String realName,
            @ApiParam(value = "邮箱", example = "admin@example.com") @RequestParam(required = false) String email,
            @ApiParam(value = "手机号", example = "13800138000") @RequestParam(required = false) String phone,
            @ApiParam(value = "用户状态", example = "1") @RequestParam(required = false) Integer status,
            @ApiParam(value = "页码", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(value = "请求ID", example = "req-20240520-8f7d9a0b") @RequestParam(required = false) String requestId,
            @ApiParam(value = "版本号", example = "1.0.0") @RequestParam(defaultValue = "1.0.0") String version) {
        
        // 初始化请求上下文
        if (requestId == null || requestId.isEmpty()) {
            requestId = RequestContext.generateRequestId();
        } else {
            RequestContext.setRequestId(requestId);
        }
        RequestContext.setVersion(version);
        
        log.info("接收到用户列表查询API请求，requestId={}, version={}, 参数：username={}, realName={}, email={}, phone={}, status={}, pageNum={}, pageSize={}", 
                requestId, version, username, realName, email, phone, status, pageNum, pageSize);
        
        try {
            // 参数校验
            if (pageNum == null || pageNum < 1) {
                return ApiResponse.badRequest("页码必须大于0", requestId, version);
            }
            if (pageSize == null || pageSize < 1) {
                return ApiResponse.badRequest("每页大小必须大于0", requestId, version);
            }
            if (pageSize > 100) {
                return ApiResponse.badRequest("每页大小不能超过100", requestId, version);
            }
            
            // 构建查询条件
            UserQuery query = new UserQuery();
            query.setUsername(username);
            query.setRealName(realName);
            query.setEmail(email);
            query.setPhone(phone);
            query.setStatus(status);
            query.setPageNum(pageNum);
            query.setPageSize(pageSize);
            
            // 调用服务层
            com.baomidou.mybatisplus.core.metadata.IPage<UserQueryVO> userPage = userService.queryUserPage(query);
            
            // 转换为API响应对象
            List<UserApiVO> apiVOList = userPage.getRecords().stream()
                    .map(this::convertToApiVO)
                    .collect(Collectors.toList());
            
            PageResponse<UserApiVO> pageResponse = new PageResponse<>(
                    apiVOList,
                    userPage.getTotal(),
                    userPage.getSize(),
                    userPage.getCurrent(),
                    userPage.getPages()
            );
            
            log.info("用户列表查询API成功，requestId={}, 返回{}条记录", requestId, userPage.getTotal());
            return ApiResponse.success(pageResponse, requestId, version);
            
        } catch (Exception e) {
            log.error("用户列表查询API异常，requestId={}", requestId, e);
            return ApiResponse.systemError("查询用户列表失败", requestId, version);
        } finally {
            RequestContext.clear();
        }
    }
    
    /**
     * 根据ID查询用户详情
     * 
     * @param id 用户ID
     * @return 用户详情
     */
    @GetMapping("/{id}")
    public ApiResponse<UserApiVO> getUserById(
            @PathVariable Long id,
            @ApiParam(value = "请求ID", example = "req-20240520-8f7d9a0b") @RequestParam(required = false) String requestId,
            @ApiParam(value = "版本号", example = "1.0.0") @RequestParam(defaultValue = "1.0.0") String version) {
        
        // 初始化请求上下文
        if (requestId == null || requestId.isEmpty()) {
            requestId = RequestContext.generateRequestId();
        } else {
            RequestContext.setRequestId(requestId);
        }
        RequestContext.setVersion(version);
        
        log.info("接收到用户详情查询API请求，requestId={}, version={}, 用户ID：{}", requestId, version, id);
        
        try {
            // 参数校验
            if (id == null || id <= 0) {
                return ApiResponse.badRequest("用户ID不能为空且必须大于0", requestId, version);
            }
            
            // 调用服务层
            UserQueryVO userVO = userService.getUserById(id);
            if (userVO == null) {
                return ApiResponse.error(404, "用户不存在", requestId, version);
            }
            
            // 转换为API响应对象
            UserApiVO apiVO = convertToApiVO(userVO);
            
            log.info("用户详情查询API成功，requestId={}, 用户ID：{}", requestId, id);
            return ApiResponse.success(apiVO, requestId, version);
            
        } catch (Exception e) {
            log.error("用户详情查询API异常，requestId={}, 用户ID：{}", requestId, id, e);
            return ApiResponse.systemError("查询用户详情失败", requestId, version);
        } finally {
            RequestContext.clear();
        }
    }
    
    /**
     * 将UserQueryVO转换为UserApiVO
     * 
     * @param userVO 用户查询VO
     * @return 用户API VO
     */
    private UserApiVO convertToApiVO(UserQueryVO userVO) {
        UserApiVO apiVO = new UserApiVO();
        BeanUtils.copyProperties(userVO, apiVO);
        return apiVO;
    }
}

